<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/12 18:42
 * @version
 */
namespace Modules\ApiV2\Controllers;

use App\Models\MobileRechargeOrder;
use App\Models\RechargeOrder;
use App\Models\ShopOrder;
use App\Models\User;
use App\Models\UserCar;
use App\Sms;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Service\Logic\CouponLogic;
use Modules\Service\Logic\OilCardLogic;
use Modules\Service\Logic\UserLogic;
use Modules\Token\Facades\Token;

class UserController extends BaseController
{
    //手机号注册
    public function mobileRegister(Request $request){
        //接收显示参数
        $mobile = trim($request->input("mobile",false));
        $nickname = $request->input("nickname",'');
        $openCode = $request->input("open_code",false);
        $password = $request->input("password",false);
        $smsCode = $request->input("sms_code",false);
        $openid = $request->input("openid",'');
        //获取客户端IP地址
        $ip = $request->getClientIp();

        //验证手机号
        if (!$mobile)return self::fail(1003,"缺少必要参数:mobile");
        //验证验证码
        if (!$smsCode)return self::fail(1003,"缺少必要参数:sms_code");
        //验证密码
        if (!$password)return self::fail(1003,"缺少必要参数:password");
        //验证密码
        if (strlen($password)<6 || strlen($password)>16)return self::fail(1003,"密码长度在6-16位之间");
        //验证手机号是否被注册
        if (!User::canUseMobile($mobile)){
            $errorData = UserLogic::errorLogRecord($mobile,$ip);
            return self::fail(1006,"手机号已注册");
        }
        //验证手机短信验证码是否正确
        if (!Sms::validation($mobile,$smsCode)){
            $errorData = UserLogic::errorLogRecord($mobile,$ip);
            return self::fail(1004,'验证码错误');
        }
        //获取推荐人ID
        $parentId = null;
        if ($openCode){
            $parent = User::findByCode($openCode);
            if ($parent) {
                $parentId = $parent->id;
            }
        }

        $android_token = '';
        $ios_token = '';
        $platform = '';
        $channel = '';
        $version = '';
        $device_id = '';
        //判断头部参数app_platform是否上传
        if($request->hasHeader('app_platform')){
            $platform = $request->header('app_platform')?:'';//应用平台
            $device_id = $request->header('device-id')?:'';//设备号
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('app_channel')?:'';//机型
            $version = $request->header('app_version')?:'';//版本
        }
        //判断头部参数platform是否上传
        if($request->hasHeader('platform')){
            $platform = $request->header('platform')?:'';
            $device_id = $request->header('device-id')?:'';
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('channel')?:'';
            $version = $request->header('version')?:'';
        }
        $bundleId = $request->header('bundle_id','youyoutong');
        $imei = $request->header('imei');
        $idfa = $request->header('idfa');

        $user = new User();
        $user->mobile = $mobile;
        $user->nickname = $nickname;
        $user->parent_id = $parentId;
        $user->password = md5($password);
        $user->app_platform = $platform;
        $user->app_version = $version;
        $user->app_channel = $channel;
        $user->ios_token = $ios_token;
        $user->android_token = $android_token;
        $user->device_code = $device_id;
        $user->client_ip = $ip;
        $user->open_id = $openid;
        $user->app = $bundleId;
        $user->os = $platform;
        $user->imei = $imei;
        $user->idfa = $idfa;
        //注册
        return UserLogic::userRegister($user);
    }

    //发送验证码
    public function sendSms(Request $request){

        //接收参数
        $mobile = $request->input('mobile',false);
        $type   = $request->input('type', '1');
        if (!$mobile)return self::fail(1003,"缺少必要参数:mobile");

//        $checkRes = $this->checkSmsApi($request);
//        if (false === $checkRes) {
//            return self::success();
//        }
//
//        $lockKey = $mobile;
//        $isLock = Cache::get($lockKey);
//        if ($isLock && 1 == $isLock) {
//            \App\Helpers\Log::write($mobile, '多次请求，已锁一分钟action:'.$type, 'sms.log');
//            return self::success();
//        } else {
//            Cache::put($lockKey, 1, 1);
//        }

        try {
            // 手机号注册
            if ($type == 1) {
                Sms::generate($mobile, Sms::TPL_REGISTER, $request->getClientIp());
            }
            //验证码登陆
            if ($type == 2) {
                Sms::generate($mobile, Sms::TPL_LOGIN, $request->getClientIp());
            }
            //修改密码
            if ($type == 3) {
                Sms::generate($mobile, Sms::TPL_CHANGE_PASSWORD, $request->getClientIp());
            }
            //绑定手机号
            if ($type == 4) {
                //查询手机号是否被绑定
                $userData = User::where("mobile",$mobile)->count();
                Sms::generate($mobile, Sms::TPL_CHECK_CODE, $request->getClientIp());
                //if ($userData)return self::fail(1011,"该手机号已绑定,继续绑定此账号将被注销");
            }

            //Cache::forget($lockKey);
            return self::success();
        } catch (\Exception $e) {
            //Cache::forget($lockKey);
            Log::info('短信发送失败，msg:'.$e->getMessage().'|'.$e->getFile().'|'.$e->getLine());
            return self::fail(400, '发送失败');
        }
    }

    //手机号登陆
    public function mobileLogin(Request $request){
        //接收参数
        $mobile = $request->input("mobile",false);
        $password = $request->input("password",false);
        $smsCode = $request->input("sms_code",false);
        $openid = $request->input("openid",'');
        //获取客户端IP地址
        $ip = $request->getClientIp();

        //验证参数的合法性
        if (!$mobile)return self::fail(1003,"缺少必要参数:mobile");
        //密码和验证码只能唯一存在
        if ($password)$smsCode=false;
        else$password=false;

        //获取隐示参数
        $android_token = '';
        $ios_token = '';
        $platform = '';
        $channel = '';
        $version = '';
        $device_id = '';
        //判断头部参数app_platform是否上传
        if($request->hasHeader('app_platform')){
            $platform = $request->header('app_platform')?:'';//应用平台
            $device_id = $request->header('device-id')?:'';//设备号
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('app_channel')?:'';//机型
            $version = $request->header('app_version')?:'';//版本
        }
        //Log::info($request->header());
        //判断头部参数platform是否上传
        if($request->hasHeader('platform')){
            $platform = $request->header('platform')?:'';
            $device_id = $request->header('device-id')?:'';
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('channel')?:'';
            $version = $request->header('version')?:'';
        }
        $array = ["openid"=>$openid,"mobile"=>$mobile,"password"=>$password,"smsCode"=>$smsCode,"ip"=>$ip,"platform"=>$platform,"ios_token"=>$ios_token,"android_token"=>$android_token,"channel"=>$channel,"version"=>$version,"device_id"=>$device_id];
        return UserLogic::userLogin($array);
    }

    //微信授权获取access_token(移动端)
    public function wxGetToken(Request $request){
        //接收参数
        $code = $request->input("code",false);
        //验证参数是否合法
        if (!$code)return self::fail(1003,"缺少必要参数:code");
        //appId和appSecret
        $appId = "wxd1233280b6b4d4d7";
        $appSecret = "265c2beefc5f9ab53d691534e3a39df7";
        //请求地址
        $host = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";
        //拉起请求
        $client = new Client();
        $response = $client->request("GET",$host,["verify"=>false]);
        if($response->getStatusCode()==200) {
            //解析返回值
            return json_decode($response->getBody()->getContents(), true);
        }else{
            return self::fail(500,"系统错误");
        }
    }


    //微信登录
    public function wxLogin(Request $request){
        //接收参数
        $access_token = $request->input("access_token",false);
        $openid = $request->input("openid",false);
        $openCode = $request->input("open_code");
        //效验参数
        if (!$access_token)return self::fail(1003,"缺少必要参数:access_token");
        if (!$openid)return self::fail(1003,"缺少必要参数:openid");
        $parentId = '';
        //获取推荐人ID
        if ($openCode){
            $parent = User::findByCode($openCode);
            $parentId = $parent->id;
        }

        //获取客户端IP地址
        $ip = $request->getClientIp();
        //获取隐示参数
        $android_token = '';
        $ios_token = '';
        $platform = '';
        $channel = '';
        $version = '';
        $device_id = '';
        //判断头部参数app_platform是否上传
        if($request->hasHeader('app_platform')){
            $platform = $request->header('app_platform')?:'';//应用平台
            $device_id = $request->header('device-id')?:'';//设备号
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('app_channel')?:'';//机型
            $version = $request->header('app_version')?:'';//版本
        }
        //判断头部参数platform是否上传
        if($request->hasHeader('platform')){
            $platform = $request->header('platform')?:'';
            $device_id = $request->header('device-id')?:'';
            $platform == 'android' && $android_token = $device_id;
            $platform == 'ios' && $ios_token = $device_id;
            $channel = $request->header('channel')?:'';
            $version = $request->header('version')?:'';
        }
        $bundleId = $request->header('bundle_id','youhuixia');
        $imei = $request->header('imei');
        $idfa = $request->header('idfa');
        //请求地址
        $host = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        //拉起请求
        $client = new Client();
        $response = $client->request("GET",$host,["verify"=>false]);
        if($response->getStatusCode()==200) {
            //解析返回值
            $data = json_decode($response->getBody()->getContents(), true);
            Log::info($data);
            if (!array_key_exists("errcode",$data)){
                $nickname = $data["nickname"];
                $nickname = json_encode($nickname);
                //查询用户
                $userData = User::where("unionid",$data['unionid'])->first();
                //判断用户是否注册
                if (!$userData) {
                    $user = new User();
                    $user->open_id = $openid;
                    $user->nickname = $nickname;
                    $user->unionid = $data['unionid'];
                    $user->avatar = $data['headimgurl'];
                    $user->parent_id = $parentId;
                    $user->app_platform = $platform;
                    $user->app_version = $version;
                    $user->app_channel = $channel;
                    $user->ios_token = $ios_token;
                    $user->android_token = $android_token;
                    $user->device_code = $device_id;
                    $user->client_ip = $ip;
                    $user->app = $bundleId;
                    $user->imei = $imei;
                    $user->idfa = $idfa;

                    return UserLogic::userRegister($user);
                }else{
                    if ($userData->cancel==1) {
                        return self::fail(1026,"该账号已被注销");
                    }
                    $param = ["id" => $userData->id, "open_id" => $openid, "mobile" => $userData->mobile, "open_code" => $userData->open_code, "ip" => $ip, "platform" => $platform, "ios_token" => $ios_token, "android_token" => $android_token, "channel" => $channel, "version" => $version, "device_id" => $device_id];
                    return UserLogic::wxLogin($param);
                }
            }else{
                return $data;
            }
        }else{
            return self::fail(500,"系统错误");
        }
    }


    //根据openid获取unionid
    public function getWeixinUnionid(Request $request){
        $openid = $request->input("openid",false);
        $access_token = $request->input("access_token",false);
        if (!$openid)return self::fail(1003,"缺少必要参数:openid");
        if (!$access_token)return self::fail(1003,"缺少必要参数:access_token");
        return UserLogic::getUnionid($openid,$access_token);
    }

    //用户信息
    public function userInfo(){
        //获取userId
        $userId = Token::data("id");
        return UserLogic::userCenter($userId);
    }

    //找回密码
    public function mobileFindPassWord(Request $request){
        try {
            $userId = Token::data("id");
            $user = User::find($userId);
            if (empty($user['mobile'])){
                return self::fail(1003, "仅限手机号注册可操作，如您是微信用户请先绑定手机号!");
            }
            //接收参数
            $mobile = $request->input("mobile", false);
            $password = $request->input("password", false);
            $smsCode = $request->input("sms_code",false);
            //验证手机号
            if (!$mobile) return self::fail(1003, "缺少必要参数:mobile");
            //验证密码
            if (!$password) return self::fail(1003, "缺少必要参数:password");
            //验证验证码
            if (!Sms::validation($mobile,$smsCode))return self::fail(1004,"验证码错误");
            if (strlen($password)<6 || strlen($password)>16)return self::fail(1003,"密码长度在6-16位之间");
            //验证手机号是否注册
            if (User::canUseMobile($mobile)) return self::fail(1009, "手机号未注册");
            return UserLogic::findPassword($mobile, $password);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //修改昵称
    public function changeNickname(Request $request){
        try {
            //获取用户信息
            $userData = User::find(Token::data("id"));
            //接收参数
            $nickname = $request->input("nickname", false);
            if (!$nickname) return self::fail(1003, "缺少必要参数:nickname");
            //传入昵称
            $userData->nickname = $nickname;
            //修改
            $userData->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //修改头像
    public function changeAvatar(Request $request){
        try{
            //获取用户信息
            $userId = Token::data("id");
            $userData = User::find($userId);
            if (!$userData)return self::fail(1014,"用户不存在");
            //获取图片ID
            $imageId = $request->input("image_id",false);
            if (!$imageId)return self::fail(1003,"缺少必要参数:image_id");
            //修改头像
            $userData->image_id = $imageId;
            $userData->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //绑定电话
    public function changeMobile(Request $request){

        try {
            //获取用户Id
            $userId = Token::data("id");
            //获取参数
            $mobile = $request->input("mobile", false);
            $smsCode = $request->input("sms_code", false);
            $password = $request->input("password",false);
            $platform = $request->header('app_platform')?:'';//应用平台
            //验证参数
            if (!$mobile) return self::fail(1003, "缺少必要参数:mobile");
            if (!$smsCode) return self::fail(1003, "缺少必要参数:sms_code");
            if (!$password) return self::fail(1003, "缺少必要参数:password");
            //if (strlen($password)<6 || strlen($password)>16)return self::fail(1003,"密码长度在6-16位之间");
            $userData = User::where("id",$userId)->first();
            if (!$userData)return self::fail(1014,"亲,请登陆后再操作!");
            //查询手机号是否被绑定
            $mobileData = User::query()->where("mobile",$mobile)->first();
            if ($userData->mobile==$mobile){
                if ($platform=='android') {
                    return self::fail(500, "亲!该手机号已绑定成功哟,请不要重复操作!");
                }else{
                    return self::fail(1037, "亲!该手机号已绑定成功哟,请不要重复操作!");
                }
            }
            if ($mobileData['open_id']!='' || $mobileData['unionid']!=''){
                if ($platform=='android') {
                    return self::fail(500, "亲!该手机号已被绑定!");
                }else{
                    return self::fail(1037,"亲!该手机号已被绑定!");
                }
            }

            //验证验证码
            if (!Sms::validation($mobile, $smsCode)) return self::fail(1004, "验证码错误");

            if (!$mobileData) {
                //赋值
                $userData->mobile = $mobile;
                $userData->password = $password;
                //修改
                $userData->save();

                //返回数据
                return success([
                    'token'     =>(new \Modules\Token\Token())->generate($userData->id, [
                        'id'        => $userData->id,
                        'mobile'    => $userData->mobile,
                        'open_code' => $userData->open_code,
                    ]),
                    'open_code' => $userData->open_code,
                    'open_id'   => $userData->open_id,
                    'mobile' => $userData->mobile
                ]);
            }else{

                //查询账户下的订单
                $rechargeCount = RechargeOrder::where("user_id",$userData->id)->where("status",'>=',0)->count();
                $mobileRechargeCount = MobileRechargeOrder::where("user_id",$userData->id)->where("status",">=",0)->count();
                $shopOrderCount = ShopOrder::where("user_id",$userData->id)->where("order_status",">=",0)->count();
                $count = $rechargeCount+$mobileRechargeCount+$shopOrderCount;

                $rechargeSum = RechargeOrder::where("user_id",$mobileData['id'])->where("status",'>=',0)->count();
                $mobileRechargeSum = MobileRechargeOrder::where("user_id",$mobileData['id'])->where("status",">=",0)->count();
                $shopOrderSum = ShopOrder::where("user_id",$mobileData['id'])->where("order_status",">=",0)->count();
                $sum = $rechargeSum+$mobileRechargeSum+$shopOrderSum;
                if ($count>0 && $sum>0){
                    if ($platform=='android'){
                        return self::fail(500, "该手机号下已有订单，无法绑定在该微信，请更换其他手机号码绑定，如还有疑问，请联系客服：400-8170-777");
                    }else {
                        return self::fail(1011, "该手机号下已有订单，无法绑定在该微信，请更换其他手机号码绑定，如还有疑问，请联系客服：400-8170-777");
                    }
                }elseif ($count>0 && $sum==0){
                    DB::beginTransaction();
                    $userData->mobile = $mobileData->mobile;
                    $userData->password = $password;
                    $userData->save();
                    $mobileData->delete();
                    DB::commit();

                    //返回数据
                    return success([
                        'token'     =>(new \Modules\Token\Token())->generate($userData->id, [
                            'id'        => $userData->id,
                            'mobile'    => $userData->mobile,
                            'open_code' => $userData->open_code,
                        ]),
                        'open_code' => $userData->open_code,
                        'open_id'   => $userData->open_id,
                        'mobile' => $userData->mobile
                    ]);
                }else{
                    DB::beginTransaction();
                    $mobileData->open_id = $userData->open_id;
                    $mobileData->unionid = $userData->unionid;
                    if ($mobileData->nickname=='' || $mobileData->nickname==null){
                        $mobileData->nickname = $userData->nickname;
                    }
                    if ($mobileData->image_id=='' || $mobileData->image_id==null){
                        $mobileData->avatar = $userData->avatar;
                    }
                    $userData->password = $password;
                    $mobileData->save();
                    $userData->delete();
                    DB::commit();
                    //返回数据
                    return success([
                        'token'     =>(new \Modules\Token\Token())->generate($mobileData->id, [
                            'id'        => $mobileData->id,
                            'mobile'    => $mobileData->mobile,
                            'open_code' => $mobileData->open_code,
                        ]),
                        'open_code' => $mobileData->open_code,
                        'open_id'   => $mobileData->open_id,
                        'mobile' => $mobileData->mobile
                    ]);
                }

            }
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::fail(500,"系统错误");
        }

    }

    //我的油卡
    public function userOilCardList(){
        //获取用户Id
        $userId = Token::data("id");
        return OilCardLogic::userHaveOilCard($userId);
    }

    //删除我的油卡
    public function userOilCardDelete(Request $request){
        //获取用户Id
        $userId = Token::data("id");
        //获取油卡Id
        $oilCardId = $request->input("old_card_id",false);
        //判断油卡是否存在
        if (!$oilCardId)return self::fail(1003,"缺少必要参数:oil_card_id");

        return OilCardLogic::userDeleteOilCard($userId,$oilCardId);
    }

    //我的优惠券
    public function userCouponList(Request $request){
        //获取用户Id
        $userId = Token::data("id");
        $page = $request->input("page",1);
        $limit = $request->input("limit",20);
        $status = $request->input("status",0);

        if (!in_array($status, [1,2,3,0])) {
            return self::fail(1003,"参数错误");
        }

        return CouponLogic::userCouponAll($userId, $status,$page,$limit);
    }

    //意见反馈
    public function userFeedBack(Request $request){
        try{
            //接收参数
            $userId  = Token::data("id");
            //查询用户
            $userData = User::find($userId);
            if (!$userData)return self::fail(1014,"用户不存在");
            $title = $request->input("title",false);
            $content = $request->input("content");
            $mobile = $request->input("mobile");
            if (!$title)return self::fail(1003,"缺少必要参数:title");

            return UserLogic::feedBack($userData->id,$title,$content,$mobile);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //我的车辆
    public function userCar(Request $request){
        $userId = Token::data("id");
        $userData = User::find($userId);
        $bundleId = $request->header("bundle_id","youyoutong");
        if (!$userData)return self::fail(1014,"用户不存在");
        return UserLogic::userCarIsMethod($userId,$bundleId);
    }

    //添加车辆
    public function userCarAdd(Request $request){
        $userId = Token::data("id");
        $userData = User::find($userId);
        if (!$userData)return self::fail(1014,"用户不存在");
        $plateNumber = $request->input("plate_number",false);
        $carModel = $request->input("car_model",false);
        $vin = $request->input("vin",false);
        $engineNumber = $request->input("engine_number",false);
        if (!$plateNumber)return self::fail(1003,"缺少必要参数:plate_number");
        if (!$carModel)return self::fail(1003,"缺少必要参数:car_model");
        if (!$vin)return self::fail(1003,"缺少必要参数:vin");
        if (!$engineNumber)return self::fail(1003,"缺少必要参数:engine_number");
        if (strlen($vin)!=6)return self::fail(1003,"车架号长度有误");
        if (strlen($engineNumber)!=6)return self::fail(1003,"发动机号长度有误");
        return UserLogic::userCarAdd($userId,$userData->mobile,$plateNumber,$carModel,$vin,$engineNumber);
    }

    //删除车辆
    public function userCarDelete(Request $request){
        $id = $request->input("id");
        if (empty($id))return self::fail(1003,"'id'未赋值");
        $result = UserLogic::userCarDelete($id);
        if (!$result){
            return self::fail(1046,"车辆删除失败");
        }
        return success();
    }

    //违章查询
    public function carLawbreaking(Request $request){
        $userId = Token::data("id");
        $userData = User::find($userId);
        if (!$userData)return self::fail(1014,"用户不存在");
        $carData = UserCar::where("user_id",$userId)->first();
        return UserLogic::lawbreaking($userId,$carData['plate_number'],$carData['car_model'],$carData['vin'],$carData['engine_number']);
    }

    /**
     * 验证_crsf
     *
     * @author yls
     * @param Request $request
     * @return bool
     */
    public function checkSmsApi(Request $request)
    {
        $appPlatform = $authorization = '';

        if ($request->hasHeader('app-platform')) {
            $appPlatform = $request->header('app-platform');
            $appPlatform = strtolower($appPlatform);
        }

        $authorization = $request->header('Authorization');

        if (in_array($appPlatform, ['ios', 'android'])) {
            return true;
        }

        if ($authorization != base64_encode('jiayouhui360.com')) {
            \App\Helpers\Log::write($request->getClientIp(), '非法请求，authorization不正确，authorization:【'.$authorization.'】', 'sms.log');
            return false;
        }
        return true;
    }

}